#include "timer.h"
uint8_t Value = 0;
uint8_t ValueChangedFlag = 0;
/**
 * @param uint16_t arr : 自动重装载;
 * @param uint16_t psc : 预分频系数;
 * @brief Tout=(arr+1)*(psc+1)/时钟频率
 * @attention APB1总线的分频系数默认2,TIM2-TIM7的时钟频率2倍频;
 * @attention Tout=(9999+1)*(7199+1)/72MHz=10^6us=1s
 */
void TIMER3_Init(uint16_t arr, uint16_t psc)
{
    TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE); // TIM3  总线时钟
    TIM_InternalClockConfig(TIM3);                       // TIM3CLK FROM RCC

    // 如果定时器选择 外部时钟
    // 选择: TIM_ETRClockMode2Config();
    // ETR 相应GPIO也要开启(一般为上拉输入);
    // 设置 自动重装载,预分频系数

    TIMER3_NVIC_Init();                                             // NVIC
    TIM_TimeBaseInitStructure.TIM_Prescaler = psc;                  // 预分频系数
    TIM_TimeBaseInitStructure.TIM_Period = arr;                     // 自动重装载
    TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up; // 向上计数
    TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
    TIM_TimeBaseInit(TIM3, &TIM_TimeBaseInitStructure); // Generate an update event to reload the Prescaler and the Repetition counter
    TIM_ClearFlag(TIM3, TIM_FLAG_Update);               // 避免刚初始化就进入中断
    TIM_ITConfig(TIM3, TIM_IT_Update, ENABLE);          // 使能TIM3更新中断
    TIM_Cmd(TIM3, ENABLE);                              // 启动TIM3
}

void TIMER3_NVIC_Init(void)
{
    NVIC_InitTypeDef NVIC_InitStructure;
    NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn;           // 中断通道
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 3; // 抢占2，子优先级3，组2
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3;        // 抢占2，子优先级3，组2
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStructure); // NVIC初始化
}

/**
 * TIM3中断服务程序
 */
void TIM3_IRQHandler(void)
{
    if (TIM_GetITStatus(TIM3, TIM_IT_Update) == SET)
    {
        Value++;
        if (Value >= 60)
        {
            Value = 0;
        }
        ValueChangedFlag = 1;
        TIM_ClearITPendingBit(TIM3, TIM_IT_Update); // 清楚标志位
    }
}

/**
 * 先调用: TIMER3_Init(9999, 7199);
 */
void TIMER3_TestCode(void)
{
    if (ValueChangedFlag)
    {

        printf("STM32 TIMER3 Printf Value=%d \r\n", Value);
        ValueChangedFlag = 0;
    }
}
